package mysql

import (
	"fmt"
	mylog "go-web-admin/logger"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type MysqlConfig struct {
	Host         string `mapstructure:"host"`
	Port         uint   `mapstructure:"port"`
	Username     string `mapstructure:"username"`
	Password     string `mapstructure:"password"`
	DatabaseName string `mapstructure:"database_name"`
	EchoSql      bool   `mapstructure:"echo_sql"`
}

var DB *gorm.DB
var Err error

func InitMysql(mysqlConfig *MysqlConfig) {

	username := mysqlConfig.Username
	password := mysqlConfig.Password
	host := mysqlConfig.Host
	port := mysqlConfig.Port
	databaseName := mysqlConfig.DatabaseName

	// dsn := "root:123456@tcp(localhost:3306)/fcsr?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, databaseName)
	DB, Err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		// 设置日志级别为Info，以便打印出所有SQL语句
		Logger: logger.Default.LogMode(logger.Info),
	})
	if Err != nil {
		mylog.Log.Errorf("数据库连接失败: %v", Err.Error())
		panic(Err)
		return
	}

	mylog.Log.Info("连接到数据库成功....")
}
